"""
用户偏好模型
支持个性化服务的用户偏好设置
"""

from datetime import datetime
from typing import Optional, Dict, Any, List
import uuid
from enum import Enum
from pydantic import BaseModel, Field
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, JSON, Float, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from src.config.database import Base


class PreferredLanguage(str, Enum):
    """用户首选语言枚举"""
    ENGLISH = "en"
    CHINESE = "zh"
    JAPANESE = "ja"
    KOREAN = "ko"
    SPANISH = "es"
    FRENCH = "fr"
    GERMAN = "de"


class PreferredModel(str, Enum):
    """用户首选模型枚举"""
    GPT4 = "gpt4"
    GPT35 = "gpt35"
    CLAUDE = "claude"
    LLAMA = "llama"
    MIXTRAL = "mixtral"
    GEMINI = "gemini"


class PreferredResponseStyle(str, Enum):
    """用户首选响应风格枚举"""
    CONCISE = "concise"  # 简洁明了
    DETAILED = "detailed"  # 详细解释
    TECHNICAL = "technical"  # 技术化
    FRIENDLY = "friendly"  # 友好亲切
    FORMAL = "formal"  # 正式规范


class UserPreference(Base):
    """用户偏好数据模型"""
    __tablename__ = "user_preferences"
    __table_args__ = {'extend_existing': True}

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), unique=True, nullable=False, index=True)
    preferred_language = Column(String(10), default=PreferredLanguage.CHINESE, nullable=False)
    preferred_model = Column(String(20), nullable=True)
    preferred_response_style = Column(String(20), default=PreferredResponseStyle.CONCISE, nullable=False)
    enable_notifications = Column(Boolean, default=True, nullable=False)
    enable_email_notifications = Column(Boolean, default=True, nullable=False)
    enable_sms_notifications = Column(Boolean, default=False, nullable=False)
    timezone = Column(String(50), default="Asia/Shanghai", nullable=False)
    theme = Column(String(20), default="light", nullable=False)
    preferred_knowledge_sources = Column(JSON, nullable=True)  # 首选知识源列表
    custom_settings = Column(JSON, nullable=True)  # 自定义设置
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    # 关系
    user = relationship("User", backref="preferences", uselist=False)

    def __repr__(self):
        return f"<UserPreference {self.id} - User {self.user_id}>"


class UserProfile(Base):
    """用户画像数据模型"""
    __tablename__ = "user_profiles"
    __table_args__ = {'extend_existing': True}

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), unique=True, nullable=False, index=True)
    frequent_topics = Column(JSON, nullable=True)  # 频繁讨论的话题
    interaction_patterns = Column(JSON, nullable=True)  # 交互模式分析
    sentiment_analysis = Column(JSON, nullable=True)  # 情感分析结果
    preference_score = Column(JSON, nullable=True)  # 偏好分数
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    # 关系
    user = relationship("User", backref="profile", uselist=False)

    def __repr__(self):
        return f"<UserProfile {self.id} - User {self.user_id}>"


# 新增的数据模型
class UserInterest(Base):
    """用户兴趣标签模型"""
    __tablename__ = "user_interests"
    __table_args__ = {'extend_existing': True}
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False, index=True)
    interest_tag = Column(String(100), nullable=False, index=True)
    weight = Column(Float, default=1.0)  # 兴趣强度
    category = Column(String(50))  # 兴趣分类
    last_interacted = Column(DateTime, default=datetime.utcnow)  # 最后交互时间
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    user = relationship("User", backref="interests")


class ContentItem(Base):
    """内容项目模型"""
    __tablename__ = "content_items"
    __table_args__ = {'extend_existing': True}
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    title = Column(String(200), nullable=False)
    description = Column(Text)
    content_type = Column(String(50), nullable=False)  # 类型: 文档、视频、问答等
    tags = Column(JSON, nullable=True)  # 内容标签
    category = Column(String(50))  # 内容分类
    content_metadata = Column('metadata', JSON, nullable=True)  # 其他元数据，避免使用保留字'metadata'
    embedding = Column(JSON, nullable=True)  # 内容向量表示
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)


class UserContentInteraction(Base):
    """用户内容交互记录模型"""
    __tablename__ = "user_content_interactions"
    __table_args__ = {'extend_existing': True}
    
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False, index=True)
    content_id = Column(UUID(as_uuid=True), ForeignKey("content_items.id"), nullable=False, index=True)
    interaction_type = Column(String(50), nullable=False)  # 查看、点击、收藏、评分等
    score = Column(Float, default=0.0)  # 交互评分
    interaction_metadata = Column('metadata', JSON, nullable=True)  # 交互元数据，避免使用保留字'metadata'
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)
    
    user = relationship("User", backref="content_interactions")
    content = relationship("ContentItem", backref="interactions")


class UserPreferenceCreate(BaseModel):
    """创建用户偏好的请求模型"""
    preferred_language: Optional[PreferredLanguage] = Field(None, description="首选语言")
    preferred_model: Optional[PreferredModel] = Field(None, description="首选模型")
    preferred_response_style: Optional[PreferredResponseStyle] = Field(None, description="首选响应风格")
    enable_notifications: Optional[bool] = Field(None, description="是否启用通知")
    enable_email_notifications: Optional[bool] = Field(None, description="是否启用邮件通知")
    enable_sms_notifications: Optional[bool] = Field(None, description="是否启用短信通知")
    timezone: Optional[str] = Field(None, description="时区")
    theme: Optional[str] = Field(None, description="主题")
    preferred_knowledge_sources: Optional[List[str]] = Field(None, description="首选知识源")
    custom_settings: Optional[Dict[str, Any]] = Field(None, description="自定义设置")


class UserPreferenceUpdate(BaseModel):
    """更新用户偏好的请求模型"""
    preferred_language: Optional[PreferredLanguage] = Field(None, description="首选语言")
    preferred_model: Optional[PreferredModel] = Field(None, description="首选模型")
    preferred_response_style: Optional[PreferredResponseStyle] = Field(None, description="首选响应风格")
    enable_notifications: Optional[bool] = Field(None, description="是否启用通知")
    enable_email_notifications: Optional[bool] = Field(None, description="是否启用邮件通知")
    enable_sms_notifications: Optional[bool] = Field(None, description="是否启用短信通知")
    timezone: Optional[str] = Field(None, description="时区")
    theme: Optional[str] = Field(None, description="主题")
    preferred_knowledge_sources: Optional[List[str]] = Field(None, description="首选知识源")
    custom_settings: Optional[Dict[str, Any]] = Field(None, description="自定义设置")


class UserPreferenceResponse(BaseModel):
    """用户偏好响应模型"""
    id: uuid.UUID
    user_id: uuid.UUID
    preferred_language: PreferredLanguage
    preferred_model: Optional[PreferredModel]
    preferred_response_style: PreferredResponseStyle
    enable_notifications: bool
    enable_email_notifications: bool
    enable_sms_notifications: bool
    timezone: str
    theme: str
    preferred_knowledge_sources: Optional[List[str]]
    custom_settings: Optional[Dict[str, Any]]
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True
        arbitrary_types_allowed = True


class UserProfileUpdate(BaseModel):
    """更新用户画像的请求模型"""
    frequent_topics: Optional[Dict[str, float]] = Field(None, description="频繁讨论的话题")
    interaction_patterns: Optional[Dict[str, Any]] = Field(None, description="交互模式分析")
    sentiment_analysis: Optional[Dict[str, float]] = Field(None, description="情感分析结果")
    preference_score: Optional[Dict[str, float]] = Field(None, description="偏好分数")


class UserProfileResponse(BaseModel):
    """用户画像响应模型"""
    id: uuid.UUID
    user_id: uuid.UUID
    frequent_topics: Optional[Dict[str, float]]
    interaction_patterns: Optional[Dict[str, Any]]
    sentiment_analysis: Optional[Dict[str, float]]
    preference_score: Optional[Dict[str, float]]
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True
        arbitrary_types_allowed = True


class RecommendationItem(BaseModel):
    """推荐项模型"""
    id: str
    type: str  # knowledge, service, article, etc.
    title: str
    description: str
    relevance_score: float
    url: Optional[str] = None
    tags: Optional[List[str]] = None


class RecommendationsResponse(BaseModel):
    """推荐结果响应模型"""
    recommendations: List[RecommendationItem]
    total_count: int